<template>
  <section class="todoapp">
    <todoHeader @add="addFn" :arr="list"></todoHeader>
    <todoMain :arr="showList" @del="delFn"></todoMain>
    <todoFooter
      :arr="list"
      @clearDone="delDone"
      @changeType="changeTypeFn"
    ></todoFooter>
  </section>
</template>

<script>
// 样式引入 + 导入组件并注册使用
import "./styles/base.css";
import "./styles/index.css";
import todoHeader from "./components/TodoHeader.vue";
import todoMain from "./components/TodoMain.vue";
import todoFooter from "./components/TodoFooter.vue";
export default {
  data() {
    return {
      type: "all",
      list: JSON.parse(localStorage.getItem("todo")) || [],
    };
  },
  components: {
    todoHeader,
    todoMain,
    todoFooter,
  },

  computed: {
    // 筛选给main传过去的数组
    showList() {
      // 未完成的  isDone为false
      if (this.type === "active") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === "complete") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
  },
  methods: {
    changeTypeFn(type) {
      this.type = type;
    },
    // 删除已完成的
    delDone() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    // 删除功能
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 添加功能
    addFn(name) {
      this.list.unshift({
        id: +new Date(),
        name,
        isDone: false,
      });
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todo", JSON.stringify(this.list));
      },
    },
  },
};
</script>
